import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import Skeleton from 'taro-skeleton'
import {Checkbox, View, Text, Navigator, Image, SwiperItem, Swiper, Block} from '@tarojs/components'
import {MEMBER_PAY, MEMBER_PAY_TOKEN, RESOURCE_URL, TARO_ENV, VIP_LIST, VIP_USER} from "../../../constants/api";
import {newHttp} from "../../../utils/request"
import {vcmonitor} from "../../../utils/tools";
import GzhAuth from "../../../components/gzh-auth/gzh-auth";
import {payment} from "../../../utils/payment.service";
import {user} from "../../../utils/user.service";
import {platform} from "../../../utils/platform-settting.service";
import './interests.scss'

export default class Integral extends Component {
  state: {
    agree: any
    priceIndex: any
    cardIndex: any
    priceList: any
    cardList: any
    showLoading: any
    userInfo: any
  } = {
    showLoading: true,
    agree: false,
    userInfo: false,
    priceIndex: 0,
    cardIndex: TARO_ENV === 'h5' ? 0 : 1,
    cardList: [],
    priceList: []
  }

  UNSAFE_componentWillMount() {
    vcmonitor(this)
  }

  async componentDidShow() {
    const platformSet: any = await platform.getSetting();
    if (!platformSet.applicationOpenVip) {
      await Taro.showToast({
        title: '您当前还未开通会员功能',
        mask: true,
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.navigateBack()
      }, 1500)
      return
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      await Taro.showToast({
        title: '你还未登录，请登录',
        mask: true,
        icon: 'none'
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    const userInfo = await newHttp.catchGet(VIP_USER, {})
    const data = await newHttp.catchGet(VIP_LIST, {})
    const cardList = data.vip || []
    let cardIndex = 0
    if (userInfo.status !== 2 && data.vip) {
      for (let i = 0; i < cardList.length; i++) {
        if (cardList[i].id === userInfo.vip_id) {
          cardIndex = i
        }
      }
    }
    setTimeout(() => {
      this.setState({cardList, priceList: data.vip_price, userInfo, showLoading: false}, async () => {
        this.setState({cardIndex})
      })
    }, 50)
  }

  async pay() {
    const {agree, cardList, priceList, priceIndex, cardIndex} = this.state
    if (!agree) {
      await Taro.vibrateShort()
      await Taro.showToast({title: '您未同意《会员服务协议》, 请同意后再购买', icon: "none", duration: 3000})
      return
    }
    if (this.paying) {
      return false
    }
    this.paying = true
    try {
      const payToken: any = await newHttp.catchPost(MEMBER_PAY_TOKEN, {
        pay_source: TARO_ENV === 'h5' ? 'gongzhonghao' : 'weapp',
        vip_id: cardList[cardIndex].id,
        price: priceList[cardList[cardIndex].id][priceIndex].price,
        price_id: priceList[cardList[cardIndex].id][priceIndex].id
      })
      if (payToken && payToken.order_num) {
        const confirmRet: any = await newHttp.catchPost(MEMBER_PAY + payToken.order_num)
        if (confirmRet) {
          const result = await payment.payment(confirmRet, false)
          if (result) {
            Taro.showToast({title: '支付成功', icon: 'success', mask: true})
            setTimeout(() => {
              Taro.redirectTo({url: '/main/my/member/order'})
            }, 1500)
          } else {
            this.paying = false
          }
        } else {
          this.paying = false
        }
      } else {
        this.paying = false
      }
    } catch (e) {
      this.paying = false
    }
  }

  isShowPayBtn(vipId, isForever, cardId) {
    return !(cardId === vipId && isForever);
  }

  ruleChange(e) {
    this.setState({agree: !e})
  }

  getMargin(val) {
    if (TARO_ENV === 'weapp' && val.length === 1) {
      return '20px'
    }
    return '30px'
  }

  bannerChange(e) {
    this.setState({priceIndex: 0, cardIndex: e.detail.current})
  }

  getBtnText(status, userLevel, cardLevel) {
    let str = '确认协议并开通会员'
    if (status !== 2 && (status === 0 || (status === 1 && userLevel === cardLevel))) {
      str = '立即续费'
    }
    return str
  }

  getSubTitle(userInfo, id) {
    if (userInfo.vip_id === id) {
      return (userInfo.access === 1 ? '' : '[赠送]') + userInfo.end_date_info
    }
    return '开通会员，畅享超低优惠体验'
  }

  paying: any = false

  render() {
    const {agree, priceIndex, priceList, cardList, cardIndex, showLoading, userInfo} = this.state
    return (
      <View className='member-page'>
        <GzhAuth />
        <Skeleton row={3} loading={showLoading} rowHeight={360}>
          <Block>
            <View className='header-bg'>
              <View className='member-card'>
                <Swiper previousMargin={this.getMargin(cardList)} circular current={cardIndex}
                  nextMargin={this.getMargin(cardList)} className='card-swiper'
                  onChange={this.bannerChange.bind(this)}
                >
                  {cardList && cardList.length > 0 && cardList.map((item, index) => {
                    return <SwiperItem
                      className={`card-swiper-item ${cardIndex === index ? 'card-swiper-item-actives' : ''} ${(cardIndex === index && TARO_ENV === 'weapp') ? 'card-swiper-item-active' : ''}`}
                      key={index}
                    >
                      <View className='member-card-wrapper'
                        style={`background: ${item.card_type === 2 ? item.card_color : `url(${item.card_url}) no-repeat`}`}
                      >
                        <View className='member-card-box'>
                          <View className='member-card-info'><Text className='member-info-title'>{item.name}</Text><Text
                            className='member-info-sub-title'
                          >{this.getSubTitle(userInfo, item.id)}</Text></View>
                          {item.card_type === 2 && <Image mode='widthFix' className='member-card-image'
                            src={`${RESOURCE_URL + '/upload/images/20220908/1662631835014_435.png'}`}
                          />}
                        </View>
                        {userInfo.status < 2 && <View className='payment-record'
                          onClick={() => Taro.navigateTo({url: '/main/my/member/order'})}
                        >缴费记录</View>}
                      </View>
                    </SwiperItem>
                  })}
                </Swiper>
              </View>
            </View>
          </Block>
        </Skeleton>
        <Skeleton row={3} loading={showLoading} rowHeight={360}>
          <Block>
            <View className='member-bottom-wrapper'>
              <View style='height: 45px;' />
              {cardList[cardIndex] && (!!cardList[cardIndex].is_vip_price || !!cardList[cardIndex].is_discount) &&
              <View className='rights-and-interests-wrapper'>
                {!!cardList[cardIndex].is_vip_price && <View className='rights-and-interests-items'>
                  <Image style='width: 48px;height: 48px;'
                    src={`${RESOURCE_URL}/upload/images/20220915/1663236141252_276.png`}
                  />
                  <Text className='rights-and-interests-text'>享会员价</Text>
                </View>}
                {!!cardList[cardIndex].is_discount && <View className='rights-and-interests-items'>
                  <Image style='width: 48px;height: 48px;'
                    src={`${RESOURCE_URL}/upload/images/20220915/1663236143312_9.png`}
                  />
                  <Text className='rights-and-interests-text'>{cardList[cardIndex].discount / 10}折</Text>
                </View>}
              </View>}
              {cardList[cardIndex] && cardList[cardIndex].id && priceList[cardList[cardIndex].id] && priceList[cardList[cardIndex].id] && priceList[cardList[cardIndex].id].length > 0 &&
              <View className='member-price'>会员价格</View>}
              {cardList && cardList.length > 0 && cardList[cardIndex] && cardList[cardIndex].id && priceList[cardList[cardIndex].id] && <View className='price-box'>
                {priceList[cardList[cardIndex].id].map((item, index) =>
                  <View onClick={() => {
                    this.setState({priceIndex: index})
                  }} key={index}
                    className={`price-items ${index === priceIndex ? 'price-active' : ''}`}
                  >
                    <View className='month'>{item.time}个月</View>
                    <View className='price-number'><Text className='price-symbol'>￥</Text><Text
                      className='price-num'
                    >{item.price}</Text></View>
                    <View className='price-bottom-number'>￥{item.month_price}/月</View>
                    {index === priceIndex && <Image className='choice-active-price'
                      src={RESOURCE_URL + '/upload/images/20220908/1662617638265_292.png'}
                    />}
                  </View>)}
              </View>}
              {cardList[cardIndex] && cardList[cardIndex].id && priceList[cardList[cardIndex].id] && priceList[cardList[cardIndex].id] && priceList[cardList[cardIndex].id].length > 0 && this.isShowPayBtn(userInfo.vip_id, userInfo.is_forever || 0, cardList[cardIndex].id) &&
              <View className='member-pay-btn-fixed'>
                <View className='confirm-open-btn'
                  onClick={() => this.pay()}
                >{this.getBtnText(userInfo.status, userInfo.level, cardList[cardIndex].level)}</View>
                <View className='agreement'>
                  <Checkbox value='true' className={`left-check-box ${TARO_ENV + 'left-check-box'}`}
                    onClick={this.ruleChange.bind(this, agree)}
                    checked={agree}
                  /><Text className='open-text-left'>开通VIP前阅读</Text><Navigator
                    url='/other/agreement/interests' className='clause'
                  >《会员服务协议》</Navigator>
                </View>
              </View>}
            </View>
          </Block>
        </Skeleton>
      </View>
    )
  }
}

